<template>
  <div class="password-form">
    <h3>🔐 修改密码</h3>
    <form @submit.prevent="changePasswordHandler">
      <div class="form-group">
        <label for="oldPassword">当前密码</label>
        <input id="oldPassword" v-model="form.oldPassword" type="password" required />
      </div>

      <div class="form-group">
        <label for="newPassword">新密码</label>
        <input id="newPassword" v-model="form.newPassword" type="password" required />
      </div>

      <div class="form-group">
        <label for="confirmPassword">确认新密码</label>
        <input id="confirmPassword" v-model="form.confirmPassword" type="password" required />
      </div>

      <div v-if="errorMsg" class="error-msg">
        {{ errorMsg }}
      </div>

      <div class="form-actions">
        <button type="submit">修改密码</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { changePassword } from '@/api/user'

const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const errorMsg = ref('')

const changePasswordHandler = async () => {
  errorMsg.value = ''

  if (form.newPassword !== form.confirmPassword) {
    errorMsg.value = '两次输入的新密码不一致'
    return
  }

  try {
    const res = changePassword(form)
    alert('密码修改成功')
    form.oldPassword = ''
    form.newPassword = ''
    form.confirmPassword = ''
  } catch (error) {
    errorMsg.value = error.message
  }
}
</script>

<style scoped>
.password-form {
  width: 100%;
  min-width: 600px;
  box-sizing: border-box;
  color : #000;
}

.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 1em;
}

.form-group label {
  width: 100px;
  margin-right: 10px;
  font-weight: bold;
  white-space: nowrap;
  color: #000;
}

.form-group input,
.form-group select {
  flex: 1;
  padding: 0.4em;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
}

.error-msg {
  color: red;
  margin-bottom: 1em;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 2em;
}

button {
  background-color: #1890ff;
  color: #fff;
  padding: 0.6em 1.2em;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #40a9ff;
}

button:active {
  background-color: #096dd9;
}
</style>
